import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:location_test/app/presentation/controllers/nmea_log_controller.dart';
import 'package:nmea_plugin/nmea_models.dart'; // [修正] 确保只导入这一个模型文件

class NmeaLogView extends GetView<NmeaLogController> {
  const NmeaLogView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('GPS 状态分析'),
        actions: [IconButton(icon: const Icon(Icons.delete_outline), tooltip: '清空日志与统计', onPressed: () => _showClearConfirmationDialog())],
      ),
      body: ListView(
        padding: const EdgeInsets.all(8.0),
        children: [_buildStatusSummaryCard(), const SizedBox(height: 8), _buildStatsCard(), const SizedBox(height: 8), _buildSnrCard()],
      ),
    );
  }

  void _showClearConfirmationDialog() {
    Get.dialog(
      AlertDialog(
        title: const Text('确认操作'),
        content: const Text('确定要清空所有NMEA日志及统计数据吗？'),
        actions: <Widget>[
          TextButton(child: const Text('取消'), onPressed: () => Get.back()),
          TextButton(
            child: const Text('清空'),
            onPressed: () {
              controller.clearHistory();
              Get.back();
            },
          ),
        ],
      ),
    );
  }

  Widget _buildStatusSummaryCard() {
    return Obx(
      () => Card(
        elevation: 2.0,
        child: Padding(
          padding: const EdgeInsets.all(10.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Text('GPS 实时状态', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
                  Chip(
                    label: Text(
                      controller.fixStatus.value,
                      style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                    ),
                    backgroundColor: controller.fixStatusColor.value,
                  ),
                ],
              ),
              const SizedBox(height: 5),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildStatusItem(Icons.satellite_alt_outlined, '卫星', '${controller.satellitesInUse.value} / ${controller.satellitesInView.value}', '在用/可见'),
                  _buildStatusItem(Icons.gps_fixed, '精度(HDOP)', controller.hdop.value.toStringAsFixed(1), '水平'),
                  _buildStatusItem(Icons.swap_vert_circle_outlined, '精度(VDOP)', controller.vdop.value.toStringAsFixed(1), '垂直'),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatusItem(IconData icon, String label, String value, String unit) {
    return Expanded(
      child: Column(
        children: [
          Icon(icon, color: Get.theme.primaryColor),
          const SizedBox(height: 4),
          Text(value, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.bold)),
          Text('$label ($unit)', style: const TextStyle(color: Colors.grey, fontSize: 12)),
        ],
      ),
    );
  }

  Widget _buildStatsCard() {
    return Card(
      elevation: 2.0,
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('数据统计', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 8),
            Obx(() => _buildMessageCounters()),
            const Divider(height: 20),
            Obx(() => _buildActiveSatellites()),
          ],
        ),
      ),
    );
  }

  Widget _buildMessageCounters() {
    if (controller.messageCounts.isEmpty) {
      return const Text('暂无报文', style: TextStyle(color: Colors.grey));
    }
    return Wrap(
      spacing: 8.0,
      runSpacing: 4.0,
      children: controller.messageCounts.entries.map((entry) {
        return Chip(label: Text('${entry.key}: ${entry.value}'), backgroundColor: Colors.blueGrey.withOpacity(0.1));
      }).toList(),
    );
  }

  Widget _buildActiveSatellites() {
    if (controller.activeSatellitePRNs.isEmpty) {
      return const Text('当前用于定位的卫星: 无', style: TextStyle(color: Colors.grey));
    }
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text('当前用于定位的卫星 (PRN):'),
        const SizedBox(height: 4),
        Wrap(
          spacing: 8.0,
          runSpacing: 4.0,
          children: controller.activeSatellitePRNs.map((prn) {
            return Chip(label: Text(prn.toString()), backgroundColor: Colors.green.withOpacity(0.2));
          }).toList(),
        ),
      ],
    );
  }

  Widget _buildSnrCard() {
    return Card(
      elevation: 2.0,
      child: Padding(
        padding: const EdgeInsets.all(12.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('可见卫星信号强度 (SNR)', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
            const SizedBox(height: 8),
            Obx(() {
              if (controller.visibleSatellites.isEmpty) {
                return const Center(
                  child: Padding(padding: EdgeInsets.all(16.0), child: Text('正在等待GSV报文...')),
                );
              }
              return SizedBox(
                height: 250,
                child: ListView.builder(
                  itemCount: controller.visibleSatellites.length,
                  itemBuilder: (context, index) {
                    return _buildSatelliteSnrBar(controller.visibleSatellites[index]);
                  },
                ),
              );
            }),
          ],
        ),
      ),
    );
  }

  // [修正] 使用正确的类型 SatelliteInfo
  Widget _buildSatelliteSnrBar(SatelliteInfo satellite) {
    final snr = satellite.snr ?? 0;
    final prn = satellite.prn;
    final color = _getColorForSnr(snr);

    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4.0),
      child: Row(
        children: [
          SizedBox(width: 60, child: Text('PRN $prn:')),
          Expanded(
            child: ClipRRect(
              borderRadius: BorderRadius.circular(8),
              child: LinearProgressIndicator(
                value: snr / 50.0, // 假设SNR最大值为50
                minHeight: 16,
                backgroundColor: color.withOpacity(0.2),
                valueColor: AlwaysStoppedAnimation<Color>(color),
              ),
            ),
          ),
          SizedBox(
            width: 40,
            child: Text(
              ' $snr',
              style: TextStyle(fontWeight: FontWeight.bold, color: color),
            ),
          ),
        ],
      ),
    );
  }

  Color _getColorForSnr(int snr) {
    if (snr > 40) return Colors.green;
    if (snr > 30) return Colors.orange;
    return Colors.red;
  }
}
